function formatData(data) {
    return data > 9 ? "" + data : "0" + data;
}

function upDateData(result, xData, yData) {
    if (result.length == 0)
        return yData;
    var index = 0;
    var beginTime = result[0].timeStamp.replace(/[ ]/g, "");
    for (; index < xData.length; index++) {
        if (xData[index] === beginTime)
            break;
    }

    for (var i = index; i >= 0 && index - i < result.length; i--)
        yData[i] = result[index - i].data;

    return yData;
}

function upDateData_2(result, xData, yData) {
    console.log(xData);
    if (result.length == 0)
        return yData;

    for (let i = 0; i < result.length; i++) {
        for (let index = 0; index < xData.length; index++) {
            if (xData[index] == result[i].timeStamp) {
                yData[index] = result[i].data;
                break;
            }
        }
    }
    return yData;
}

function setOption(chartInstance, xData, yData) {
    chartInstance.setOption({
        xAxis: { data: xData },
        series: [
            { data: yData }
        ]
    });
}


const fft = require("../js/fft/fft");
function getFreq(fs, data) {
    let fft_data = new fft.ComplexArray(data);
    let freqAmp = fft.FFT(fft_data);
    freqAmp = freqAmp.magnitude();

    let L = freqAmp.length >> 1;

    let yData = [];
    let xData = [];

    for (let i = 0; i < L + 1; i++) {
        xData.push(i * ((fs / 2) / L));
    }

    for (let i = 0; i < L + 1; i++) {
        if (i == 0 || i == L) {
            yData.push(freqAmp[i]);
        }
        else {
            yData.push(2 * freqAmp[i]);
        }
    }

    for (let i = 0; i < L + 1; i++) {
        yData[i] = yData[i].toString();
    }

    return [xData, yData];
}

module.exports.formatData = formatData;
module.exports.upDateData = upDateData;
module.exports.upDateData_2 = upDateData_2;
module.exports.setOption = setOption;
module.exports.getFreq = getFreq;